package cn.concurrence.productconsume;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 题:多线程情况下，按顺序执行，线程A 执行5 线程B 执行6次， 线程C 执行7次,循环10次
 *
 * @author summit
 * @since 2022/4/25 17:38
 */
public class ConditionTest {

	private Integer flag = 1;

	private Lock lock = new ReentrantLock();

	private Condition c1 = lock.newCondition();

	private Condition c2 = lock.newCondition();

	private Condition c3 = lock.newCondition();

	private void c1() throws InterruptedException {
		lock.lock();
		try {
			while (flag != 1) {
				c1.await();
			}
			for (int i = 0; i < 5; i++) {
				System.out.println("A =>" + i);
			}
			flag = 2;
			c2.signal();
		} finally {
			lock.unlock();
		}
	}


	private void c2() throws InterruptedException {
		lock.lock();
		try {
			while (flag != 2) {
				c2.await();
			}
			for (int i = 0; i < 6; i++) {
				System.out.println("B =>" + i);
			}
			flag = 3;
			c3.signal();
		} finally {
			lock.unlock();
		}
	}

	private void c3() throws InterruptedException {
		lock.lock();
		try {
			while (flag != 3) {
				c3.await();
			}
			for (int i = 0; i < 7; i++) {
				System.out.println("C =>" + i);
			}
			flag = 1;
			c1.signal();
		} finally {
			lock.unlock();
		}
	}

	public static void main(String[] args) {
		ConditionTest ct = new ConditionTest();
		for (int i = 0; i < 10; i++) {
			new Thread(() -> {
				try {
					ct.c1();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}).start();
		}

		for (int i = 0; i < 10; i++) {
			new Thread(() -> {
				try {
					ct.c2();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}).start();
		}

		for (int i = 0; i < 10; i++) {
			new Thread(() -> {
				try {
					ct.c3();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}).start();
		}
	}
}
